﻿
/*jslint */
/*global openDatabase: true, $: true */
/* this must have the dataService included between you can work with DB functionality */
"use strict";

var phoneContactService = (function () {
     var _contacts;

    function errorHandler(transaction, error) {
        console.log('Oops. Error was ' + error.message + ' (Code ' + error.code + ')');
        return true;
    }

    function errorHandlerSimple(error) {
        console.log('Oops. Error was ' + error.message + ' (Code ' + error.code + ')');
        return true;
    }

    function onSuccess_getContacts_FromDevice(contacts,test) {
        console.log('entering onSuccess_getContacts_FromDevice');
        console.log(contacts);
        
        for (var i = 0; i < contacts.length; i++) {

            //let's call the dataservice to save here because we don't know how to saveback
            console.log((contacts[i].displayName));

        }
        console.log('exiting onSuccess_getContacts_FromDevice');
      

    }

    // onError: Failed to get the contacts
    //
    function onError_getContacts_FromDevice(contactError) {
        console.log('I failed it');

    }

    return {

        //Initialise the database
        getContacts_FromDevice: function ( successCallback, errorCallBack ) {
            console.log('entering getContacts_FromDevice');

            // specify contact search criteria
            var options = new ContactFindOptions();
            options.filter = "";          // empty search string returns all contacts
            options.limit = "";           //no limit
            options.multiple = true;      // return multiple results
            var fields = ["displayName", "name", "emails", "phoneNumbers", "photos"];   // return contact.displayName field

            // find contacts
            navigator.contacts.find(
                                    fields,
                                    successCallback,
                                    errorCallBack,
                                    options
                                    );
            console.log('exiting getContacts_FromDevice');

            return false;
        },

        



        // Delete table from database
        dropTable: function () {
            db.transaction(
                function (transaction) {
                    transaction.executeSql("DROP TABLE contacts", [], null, errorHandler);
                }
            );
        },

        contacts: function () {
            return _contacts;
        }

    };
}());

